package cn.com.anypay.manager.common.controller;

import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.common.enums.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 基础控制器类
 * 提供通用的响应方法和异常处理
 */
public abstract class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 成功响应
     */
    protected <T> ApiResponse<T> success() {
        return ApiResponse.success();
    }

    /**
     * 成功响应（带数据）
     */
    protected <T> ApiResponse<T> success(T data) {
        return ApiResponse.success(data);
    }

    /**
     * 成功响应（带消息和数据）
     */
    protected <T> ApiResponse<T> success(String message, T data) {
        return ApiResponse.success(message, data);
    }

    /**
     * 失败响应
     */
    protected <T> ApiResponse<T> fail() {
        return ApiResponse.fail();
    }

    /**
     * 失败响应（带消息）
     */
    protected <T> ApiResponse<T> fail(String message) {
        return ApiResponse.fail(message);
    }

    /**
     * 失败响应（带结果码）
     */
    protected <T> ApiResponse<T> fail(ResultCode resultCode) {
        return ApiResponse.fail(resultCode);
    }

    /**
     * 失败响应（带结果码和消息）
     */
    protected <T> ApiResponse<T> fail(ResultCode resultCode, String message) {
        return ApiResponse.fail(resultCode, message);
    }

    /**
     * 获取客户端IP地址
     */
    protected String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }

    /**
     * 获取用户代理信息
     */
    protected String getUserAgent(HttpServletRequest request) {
        return request.getHeader("User-Agent");
    }

    /**
     * 生成请求追踪ID
     */
    protected String generateTraceId() {
        return java.util.UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 设置响应追踪ID
     */
    protected <T> ApiResponse<T> withTraceId(ApiResponse<T> response) {
        response.setRequestId(generateTraceId());
        return response;
    }

    /**
     * 成功响应（带追踪ID）
     */
    protected <T> ApiResponse<T> successWithTrace(T data) {
        return withTraceId(success(data));
    }
}